package com.ibeetl.cms.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.util.*;
import com.ibeetl.cms.entity.*;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.web.query.*;

/**
 * XxdItem 接口
 */
@Controller
public class XxdItemController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/xxdItem";

    @Autowired
    private SolrClient client;

    @Autowired private XxdItemService xxdItemService;
    
    @Autowired
    FileService fileService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("cms.xxdItem.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/xxdItem/index.html") ;
        view.addObject("search", XxdItemQuery.class.getName());
        view.addObject("templatePath","cms/xxdItem/Item_template.xlsx");
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("cms.xxdItem.edit")
    @ResponseBody
    public ModelAndView edit(Long id) {
        ModelAndView view = new ModelAndView("/cms/xxdItem/edit.html");
        XxdItem xxdItem = xxdItemService.queryById(id);
        view.addObject("xxdItem", xxdItem);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("cms.xxdItem.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/xxdItem/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("cms.xxdItem.query")
    @ResponseBody
    public JsonResult<PageQuery> list(XxdItemQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        xxdItemService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("cms.xxdItem.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)XxdItem item) throws IOException, SolrServerException {
        item.setStatus(1);
        item.setCreated(new Date());
        item.setUpdated(new Date());
        xxdItemService.save(item);
        SolrInputDocument doc = new SolrInputDocument();
        doc.setField("id", item.getId());
        doc.setField("price", item.getPrice());
        doc.setField("num", item.getNum());
        doc.setField("newPrice", item.getNewPrice());
        doc.setField("sellPoint", item.getSellPoint());
        doc.setField("status", item.getStatus());
        doc.setField("cid", item.getCid());
        doc.setField("image", item.getImage());
        doc.setField("title", item.getTitle());
        doc.setField("created", item.getCreated());
        doc.setField("updated", item.getUpdated());
        try {
            client.add("xxd_solr", doc);
            client.commit("xxd_solr");
        }catch (Exception e){

        }

        return JsonResult.success();
    }

    @PostMapping(MODEL + "/edit.json")
    @Function("cms.xxdItem.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  XxdItem item) throws IOException, SolrServerException {
        item.setUpdated(new Date());
        boolean success = xxdItemService.update(item);
        if (success) {
            try {
                SolrInputDocument doc = new SolrInputDocument();
                doc.setField("id", item.getId());
                doc.setField("price", item.getPrice());
                doc.setField("num", item.getNum());
                doc.setField("newPrice", item.getNewPrice());
                doc.setField("sellPoint", item.getSellPoint());
                doc.setField("status", item.getStatus());
                doc.setField("cid", item.getCid());
                doc.setField("image", item.getImage());
                doc.setField("title", item.getTitle());
                doc.setField("created", item.getCreated());
                doc.setField("updated", item.getUpdated());
                client.add("xxd_solr", doc);
                client.commit("xxd_solr");

                return JsonResult.success();
            }catch (Exception e){
                return JsonResult.success();
            }
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    @RequestMapping(MODEL + "/update.do")
    @Function("cms.xxdItem.add")
    @ResponseBody
    public JsonResult<String> updateItem(String id,Long newPrice) throws IOException, SolrServerException {
        XxdItem item = xxdItemService.queryById(id);
        item.setNewPrice(newPrice);
        boolean update = xxdItemService.update(item);
        try {
            if(update == true){
                SolrInputDocument doc = new SolrInputDocument();
                doc.setField("id", item.getId());
                doc.setField("price", item.getPrice());
                doc.setField("num", item.getNum());
                doc.setField("newPrice", item.getNewPrice());
                doc.setField("sellPoint", item.getSellPoint());
                doc.setField("status", item.getStatus());
                doc.setField("cid", item.getCid());
                doc.setField("image", item.getImage());
                doc.setField("title", item.getTitle());
                doc.setField("created", item.getCreated());
                doc.setField("updated", item.getUpdated());

                client.add("xxd_solr", doc);
                client.commit("xxd_solr");
                return JsonResult.success();
            }
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.success();
        }

            return JsonResult.failMessage("内部错误！");
    }


   
    @GetMapping(MODEL + "/view.json")
    @Function("cms.xxdItem.query")
    @ResponseBody
    public JsonResult<XxdItem>queryInfo(Long id) {
        XxdItem xxdItem = xxdItemService.queryById( id);
        return  JsonResult.success(xxdItem);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("cms.xxdItem.delete")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        xxdItemService.batchDelXxdItem(idList);
        return JsonResult.success();
    }
    
    
    @PostMapping(MODEL + "/excel/export.json")
    @Function("cms.xxdItem.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,XxdItemQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此xxdItemService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/admin/cms/xxdItem/Item.xls";
        PageQuery<XxdItem> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<XxdItem> list =xxdItemService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("商品列表_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping(MODEL + "/excel/import.do")
    @Function("cms.xxdItem.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
           return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        InputStream inputXML = Thread.currentThread().getContextClassLoader().getResourceAsStream("excelTemplates/admin/cms/xxdItem/Item.xml");
        XLSReader mainReader = ReaderBuilder.buildFromXML( inputXML );
        InputStream inputXLS = ins;
        List<XxdItem> list = new ArrayList<>();
        Map beans = new HashMap();
        beans.put("list", list);
        ReaderConfig.getInstance().setSkipErrors( true );
        XLSReadStatus readStatus = mainReader.read( inputXLS, beans);
        List<XLSReadMessage>  errors = readStatus.getReadMessages();
        if(!errors.isEmpty()) {
            return JsonResult.failMessage("解析excel出错");
        }
        List<XxdItem> saveList = new ArrayList<>();
        try {
            if(list == null || list.size() == 0){
                throw new PlatformException("请填写必要属性");
            }
            Iterator<XxdItem> iterator = list.iterator();
            while (iterator.hasNext()){
                XxdItem item = iterator.next();
                String title = item.getTitle();
                String sellPoint = item.getSellPoint();
                Integer num = item.getNum();
                Long price = item.getPrice();
                item.setStatus(2);
                item.setUpdated(new Date());
                //查找字段是否为空
                if(title == null || sellPoint== null || num == null || price == null){
                    throw new PlatformException("excel表格必填字段不能为空");
                }
                saveList.add(item);
            }
            this.xxdItemService.batchInsert(saveList);
            return JsonResult.success();
        }catch(Exception ex) {
            return JsonResult.failMessage("导入失败:"+ex.getMessage());
        }finally {
            ins.close();
        }
    }

    @GetMapping(MODEL + "/details.do")
    @Function("cms.xxdItem.details")
    @ResponseBody
    public ModelAndView details(Long id) {
        ModelAndView view = new ModelAndView("/cms/xxdItem/details.html");
        XxdItem item = xxdItemService.queryById(id);
        view.addObject("item", item);
        return view;
    }

    @RequestMapping(MODEL + "/down.do")
    @Function("cms.xxdItem.down")
    @ResponseBody
    public Boolean down(Long id) throws Exception{
        XxdItem item = xxdItemService.queryById(id);
        if(item != null){
            client.deleteById("xxd_solr", id+"");
            client.commit("xxd_solr");
            item.setStatus(2);
            return xxdItemService.updateTemplate(item);
        }

        return false;
    }
    

}
